﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;

using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Collections;
using System.Reflection;
using System.IO;
using System.Threading;
using System.Net;

namespace INSAForManagers
{
    public partial class FormMAdd : Form
    {
        FormMain parent;
        public FormMAdd(FormMain p)
        {
            InitializeComponent();

            parent = p;

            //대상자 구분 기본값 설정
            setTargetType(cboTargetType, parent.tscTargetType.SelectedIndex);

            //과목 목록 설정
            setSubject();

            
        }

        /*********************************
         * 이벤트 모음
         *********************************/

        private void btnClose_Click(object sender, EventArgs e)
        {
            //폼 닫기
            this.Close();

            FormMain.setMnuMAddEnabled();

            parent.stateRefresh();

        }

        //저장 버튼 클릭
        private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtPCode.Text.Length == 0)
                {
                    MessageBox.Show("개인번호를 입력하세요!    ", "확인", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtPCode.Focus();
                    return;
                }

                if (txtPCode.Text.Substring(0, 1).Equals("d") == true)
                {
                    txtPCode.Text = txtPCode.Text.ToUpper();
                }

                if (txtPCode.Text.Length != 10)
                {
                    MessageBox.Show("개인번호가 적절하지 않습니다!    ", "확인", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtPCode.Focus();
                    return;
                }

                if (txtName.Text.Length < 2)
                {
                    MessageBox.Show("성명을 입력하세요!    ", "확인", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtName.Focus();
                    return;
                }

                
                string pcode = txtPCode.Text;
                string name = txtName.Text;
                string sex = "";
                if (rdoMan.Checked == true)
                {
                    sex = "남";
                }
                else
                {
                    sex = "여";
                }

                string subject = (string)cboSubject.Items[cboSubject.SelectedIndex];

                Util.addMTargetAdd(getTargetType(), pcode, name, sex, subject);

                setFormReset();

                setListView(getTargetType());

                txtPCode.Focus();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void cboSubjectGroup_SelectionChangeCommitted(object sender, EventArgs e)
        {
            setSubject();
        }


        private void lnkPNo_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Form f = new HFormPNo();
            f.ShowDialog();
        }

        //폼 로드될 때
        private void FormMAdd_Load(object sender, EventArgs e)
        {
            try
            {
                setListView((int)getTargetType());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private byte getTargetType()
        {
            if (parent.tscTargetType.SelectedIndex == -1)
            {
                return (byte)0;
            }
            else
            {
                return (byte)parent.tscTargetType.SelectedIndex;
            }
        }

        //삭제 버튼 클릭
        private void btnDel_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("선택한 다면평가대상자 정보를 삭제할까요?   ", "확인", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
            {
                return;
            }
            try
            {
                ListView.SelectedListViewItemCollection select = lstView.SelectedItems;
                foreach (ListViewItem item in select)
                {
                    DBUtil.deleteMTargetInfo(item.SubItems[1].Text);
                    setFormReset();
                    setListView((int)getTargetType());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
       

        private void lstView_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }


        private void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                //다면평가대상자 수 확인
                int cnt = lstView.Items.Count;
                if (cnt == 0)
                {
                    MessageBox.Show("내보내기할 다면평가대상자가 없습니다.   ", "확인", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (cboTargetType.SelectedIndex == 6)
                {
                    MessageBox.Show("대상자 유형을 전체로 내보낼 수 없습니다.   ", "확인", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                Thread t = new Thread(new ThreadStart(outputMTagetXls));
                t.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "확인", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }


        private void lnkNew_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            setFormReset();
        }

        /*********************************
         * 메서드 모음
         *********************************/

        //엑셀 열기
        private void openXls()
        {
            //엑셀로드
            string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            Util.OSheet = Util.openXls(path + "\\MultiTarget");
            Util.OExcel.Visible = false;
        }

        //대상자 설정
        private void setTargetType(ComboBox cboTargetType, int index)
        {
            /*
             * 기본값으로 일반 을 선택
             * */
            cboTargetType.SelectedIndex = index;

        }

        /// <summary>
        /// 교과목 설정
        /// </summary>
        private void setSubject()
        {

            //과목 세팅          
            ArrayList list = DBUtil.getSubjectList();
            cboSubject.Items.Clear();

            if (list != null)
            {
                foreach (String data in list)
                {
                    cboSubject.Items.Add(data);
                }
            }

        }

        /// <summary>
        /// 해당 유형의 다면평가대상자 목록을 ListBox에 표시한다.
        /// </summary>
        /// <param name="targetType">대상자 유형</param>
        private void setListView(int targetType)
        {
            ArrayList list = new ArrayList();

            if (targetType == 6)
            {
                list = DBUtil.getMTargetList();
            }
            else
            {
                list = DBUtil.getMTargetList((byte)targetType);
            }
            
            lstView.Items.Clear();
            int i = 1;
            foreach (Hashtable tmp in list)
            {
                ListViewItem item = new ListViewItem(i.ToString());
                item.SubItems.Add((string)tmp["TARGET_PCODE"]);
                item.SubItems.Add((string)tmp["TARGET_NAME"]);
                item.SubItems.Add((string)tmp["TARGET_SEX"]);
                item.SubItems.Add((string)tmp["TARGET_SUBJECT"]);

                lstView.Items.Add(item);

                i++;
            }
        }

        /// <summary>
        /// 폼 리셋
        /// </summary>
        private void setFormReset() {

            txtPCode.Text = "";
            txtName.Text = "";
            rdoMan.Checked = true;
            cboSubject.SelectedIndex = -1;
        
        }

        private void outputMTagetXls() 
        {
            
            if (MessageBox.Show("현재까지 등록한 다면평가대상자(" + (string)cboTargetType.Items[(int)getTargetType()] + ") 정보를 엑셀 파일로 내보낼까요?   ", "확인", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
            {
                return;
            }

            try
            {
                //다면평가대상자 내보낼 빈 양식 파일 열기
                Util.openXls(Config.Path + "\\MultiTarget");

                //대상자 인원수
                int cnt = DBUtil.getMTargetCount(getTargetType());                

                //영역 선택
                Excel.Range range = Util.OSheet.get_Range("A4", "F250");
                //지우기
                range.set_Value(Missing.Value, "");

                //DB에서 다면평가 대상자 불러오기
                ArrayList arr = DBUtil.getMTargetInfoList(getTargetType());
                int i = 1;
                foreach (ArrayList tmp in arr)
                {
                    tmp.Insert(0, i);
                    range = Util.OSheet.get_Range("A" + (3 + i).ToString(), "F" + (3 + i).ToString());
                    range.set_Value(Missing.Value, tmp.ToArray());
                    i++;
                }                

                string myDocPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

                if (File.Exists(myDocPath + "\\다면평가대상자(" + (string)cboTargetType.Items[(int)getTargetType()] + ").xls") == true)
                {
                    File.Delete(myDocPath + "\\다면평가대상자(" + (string)cboTargetType.Items[(int)getTargetType()] + ").xls");
                }

                Util.OWorkBook.SaveAs(myDocPath + "\\다면평가대상자(" + (string)cboTargetType.Items[(int)getTargetType()] + ").xls", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                
                MessageBox.Show("다면평가대상자 파일을 [내문서]에 내보냈습니다.     \n\n다면평가자에게 배포하십시오.", "확인", MessageBoxButtons.OK, MessageBoxIcon.Information);

                Util.closeXls();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void lnkFormDownload_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                SaveFileDialog dlg = new SaveFileDialog();
                dlg.Filter = "엑셀 파일(*.xls) | *.xls";
                dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    WebClient client = new WebClient();
                    client.DownloadFile(Application.StartupPath + "\\MultiExample.xls", dlg.FileName);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            MessageBox.Show("내문서에 다면평가일괄입력용 양식 파일을 다운로드하였습니다.   ", "확인", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void lnkUpload_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                OpenFileDialog dlg = new OpenFileDialog();
                dlg.Filter = "엑셀 파일(*.xls) | *.xls";
                dlg.Multiselect = false;
                dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    Util.openXls(dlg.FileName);

                    Thread t = new Thread(new ThreadStart(readMTargetXls));
                    t.Start();

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "확인", MessageBoxButtons.OK, MessageBoxIcon.Error);                
            }
        }

        /// <summary>
        /// 다면평가대상자 엑셀 파일 읽기
        /// </summary>
        private void readMTargetXls()
        {
            try
            {

                Excel.Range range;

                //마지막 열번호
                int maxRow = Util.lastRow();
                
                //시트 데이터 영역을 읽음
                range = Util.OSheet.get_Range("A4", "F" + maxRow);

                //2차원 배열로 값을 가져옴
                object[,] data = (object[,])range.get_Value(Missing.Value);

                //모든 레코드를 DB에 저장
                for (int i = 1; i <= data.GetUpperBound(0); i++)
                {
                    if (data[i, 1] != null)
                    {
                        Util.addMTargetAdd(Int32.Parse(data[i, 2].ToString()), data[i, 3].ToString(), data[i, 4].ToString(), data[i, 5].ToString(), data[i, 6].ToString());
                    }
                    else
                    {
                        continue;
                    }
                }

                //다면평가대상자 목록 갱신
                setListView((int)getTargetType());

                Util.closeXls();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            MessageBox.Show("엑셀 파일을 모두 읽었습니다.  ", "확인", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void cboTargetType_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                //전체가 아닌 경우에만 메뉴의 대상자 유형과 일치 시킴
                if (!((string)cboTargetType.SelectedItem).Equals("전체"))
                {
                    parent.tscTargetType.SelectedIndex = cboTargetType.SelectedIndex;
                    setListView((int)getTargetType());
                }
                else
                {
                    setListView(6);
                }

                                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
        }

        private void lstView_Click(object sender, EventArgs e)
        {
            ListView.SelectedListViewItemCollection select = lstView.SelectedItems;
            foreach (ListViewItem tmp in select)
            {

                txtPCode.Text = tmp.SubItems[1].Text;
                txtName.Text = tmp.SubItems[2].Text;
                if (tmp.SubItems[3].Text == "남")
                {
                    rdoMan.Checked = true;
                }
                else
                {
                    rdoWoman.Checked = true;
                }
                cboSubject.SelectedItem = tmp.SubItems[4].Text;

            }
        }
       
    }

    
}
